
searchParams = {
    stations: [],
    timeInterval: '',
    ticketsData: [],

    clear: function () {
        this.timeInterval = ''
        this.stations = []
    }
}

// 查询历史
searchHistory = {}

_searchParams = {
    stations: [],
    timeInterval: '',
    ticketsData: [],
}

// 定义一个 setter，用于监听 myVariable 的变化
Object.defineProperty(searchParams, 'timeInterval', {
    set: function(newValue) {
        _searchParams.timeInterval = newValue
        filterTicket()
    },
    get: function () {
        return _searchParams.timeInterval
    }
});

Object.defineProperty(searchParams, 'stations', {
    set: function(newValue) {
        _searchParams.stations = newValue
        filterTicket()
    },
    get: function () {
        return _searchParams.stations
    }
});

// 定义一个 setter，用于监听 myVariable 的变化
Object.defineProperty(searchParams, 'ticketsData', {
    set: function(newValue) {
    }
});

function filterTicket() {
    console.log('filterTicket')
    const tableBody = $('#ticketList tbody');
    $.each(tableBody.children(), (index, item)=>{
        const tr = $(item)
        let flag = true
        if (! tr.children()[4].innerText.startsWith(searchParams.timeInterval)) {
            flag = false
        }
        if(searchParams.stations.length > 0) {
            const start = searchParams.stations.filter(f=>f.startsWith('0')).map(m=>m.split(':')[1])
            const end = searchParams.stations.filter(f=>f.startsWith('1')).map(m=>m.split(':')[1])
            if (start.length > 0 && start.indexOf(tr.children()[2].innerText) === -1) {
                flag = false
            }
            if (end.length > 0 && end.indexOf(tr.children()[3].innerText) === -1) {
                flag = false
            }
        }
        if(flag) {
            tr.show()
        } else {
            tr.hide()
        }
    })

    const selectOptions = $('#trainNoSelect');
    $.each(selectOptions.children(), (index, item)=>{
        const startTime = $(item).attr('startTime')
        if (startTime.startsWith(searchParams.timeInterval)) {
            $(item).show()
        } else {
            $(item).hide()
        }
    })

}

$(document).ready(()=>{

    configStore.get(['from', 'to', 'trainNo', 'date', 'loginName', 'lastCode'], (result)=>{

        if(result.from) {
            $('#getOnStation').val(result.from)
            $('#getOnStationOrder').val(result.from)
        }
        if(result.to) {
            $('#toStation').val(result.to)
            $('#toStationOrder').val(result.to)
        }
        if(result.date) {
            $('#date').val(result.date)
            $('#dateOrder').val(result.date)
        }
        if(result.trainNo) {
            $('#trainNoAll').val(result.trainNo)
        }
        if(result.loginName) {
            $('#loginName').val(result.loginName)
        }
        if(result.lastCode) {
            $('#lastCode').val(result.lastCode)
        }
    })

    ticketApi.loginInfo((data)=> {
        const login = data.data
        if(! login.user_name) {
            alert('请先登录12306.')
            return
        }

        ticketApi.userInfo(user=>{
            $('#loginName').val(user.data.user_name)
        })

        const loginName = login.user_name
        $("#loginUser").hide()
        $("#userName").text(loginName)
        ticketApi.getPassenger().then(passengers=>{
            globalConfig.passengers = passengers
            const seatSelect = $('#passengers');
            seatSelect.empty()
            // 遍历数据数组，为每个数据项创建一个<option>元素并添加到<select>中
            $.each(passengers, function(index, item) {

                const e = $(`
                <div class="form-check " style="margin-left: 15px">
                        <input class="form-check-input passengers-check "  type="checkbox" value="${index}" id="passengers-${index}">
                        <label class="form-check-label  " for="passengers-${index}">
                            ${item.passenger_name}
                        </label>
                </div>
                `)
                e.insertBefore(seatSelect);
            });
        })
    })

    $('#date').val(utils.toDay())

    $.datepicker.regional['zh-CN'] = {
        clearText: '清除',
        clearStatus: '清除已选日期',
        closeText: '关闭',
        closeStatus: '不改变当前选择',
        prevText: '< 上月',
        prevStatus: '显示上月',
        prevBigText: '<<',
        prevBigStatus: '显示上一年',
        nextText: '下月>',
        nextStatus: '显示下月',
        nextBigText: '>>',
        nextBigStatus: '显示下一年',
        currentText: '今天',
        currentStatus: '显示本月',
        monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
        monthNamesShort: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'],
        monthStatus: '选择月份',
        yearStatus: '选择年份',
        weekHeader: '周',
        weekStatus: '年内周次',
        dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
        dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
        dayNamesMin: ['日','一','二','三','四','五','六'],
        dayStatus: '设置 DD 为一周起始',
        dateStatus: '选择 m月 d日, DD',
        dateFormat: 'yy-mm-dd',
        firstDay: 1,
        initStatus: '请选择日期',
        isRTL: false
    };
    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);

    $("#date").datepicker({
        dateFormat: 'yy-mm-dd',
        minDate: 0, // 只允许选择当前日期之后的日期
        maxDate: '+14D', // 允许选择一个月后的日期
        // changeMonth: true,
        // changeYear: true,
        regional: 'zh',
    });

    $("#dateOrder").datepicker({
        dateFormat: 'yy-mm-dd',
        minDate: 0, // 只允许选择当前日期之后的日期
        maxDate: '+14D', // 允许选择一个月后的日期
        // changeMonth: true,
        // changeYear: true,
        regional: 'zh',
    });

    // for(let i = 0; i < 15; i++) {
    //     const e = $(`
    //         <div class="form-check ml-2" style="margin-left: 10px">
    //             <input class="form-check-input date-checkbox" type="checkbox" value="${addDaysByYear(new Date(), i)}" id="date-checkbox${i}"  >
    //             <label class="form-check-label" for="date-checkbox${i}">
    //                 ${addDays(new Date(), i)}
    //             </label>
    //         </div>`)
    //     $("#dateOrder").append(e)
    // }

    // $( "button" ).button();

    $("#getOnStation").autocomplete({
        source: (request, response)=>{
            // 自定义过滤逻辑，这里简单示例从availableTags中过滤出匹配的项
            const filteredTags = $.grep(stationNames, function(tag) {
                 return tag.cityName.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.pinyinFull.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.stationName.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.pinyinSimple.toLowerCase().indexOf(request.term.toLowerCase()) !== -1
            });

            // 调用response函数并传递过滤后的数组
            response(filteredTags.splice(0, 10).map(e=>`${e.cityName}/${e.stationName}`));
        },
    })

    $("#toStation").autocomplete({
        source: (request, response)=>{
            const filteredTags = $.grep(stationNames, function(tag) {
                return tag.cityName.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.pinyinFull.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.stationName.toLowerCase().indexOf(request.term.toLowerCase()) !== -1 ||
                    tag.pinyinSimple.toLowerCase().indexOf(request.term.toLowerCase()) !== -1
            });

            response(filteredTags.splice(0, 10).map(e=>`${e.cityName}/${e.stationName}`));
        },
    });

    configStore.get(['searchHistory'], function (result) {
        searchHistory = result.searchHistory ? JSON.parse(result.searchHistory) : {}
        // configStore.set('searchHistory', JSON.stringify(searchHistory))
        showHistory()
    })
})

$('#newTable').click(()=>{
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        // if (popupWindowId === null || chrome.extension.getViews({ type: "popup" }).length === 0) {
        //     // 如果弹窗不存在，则创建一个新的弹窗
        //     chrome.windows.create({
        //       type: "popup",
        //       url: "popup.html",
        //       width: 500,
        //       height: 800
        //     }, function(window) {
        //       popupWindowId = window.id;
        //     });
        //   } else {
        //     // 如果弹窗已存在，则激活它
        //     chrome.windows.update(popupWindowId, { focused: true });
        //   }
        chrome.tabs.create({ url: '/main.html' })
      });
})

function getTime() {
    const d = new Date()

    return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`
}

// return mm-dd
function addDays(d, days) {
    d.setDate(d.getDate() + days)
    return `${('0' + (d.getMonth() + 1)).slice(-2)}-${('0' + d.getDate()).slice(-2)}`
}

// return yyyy-mm-dd
function addDaysByYear(d, days) {
    d.setDate(d.getDate() + days)
    return `${d.getFullYear()}-${('0' + (d.getMonth() + 1)).slice(-2)}-${('0' + d.getDate()).slice(-2)}`
}

function ticketCss(value) {

    const css = {
        'font-weight': 'normal',
    }

    css.color = 'red'

    if(value === '有') {
        css.color = 'limegreen'
    } else if (parseInt(value)) {
        css.color = 'green'
    }
    return Object.keys(css).map(e=>e + ':' + css[e]).join(';')
}

$('#startTask').click(async () => {
    stop = false
    utils.log('startTask => 开始抢票')

    const forms = $('.needs-validation')

    // Loop over them and prevent submission
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
            }

            form.classList.add('was-validated')
        }, false)
    })

    const no = $('#trainNoSelect').val().trim()

    const f = $('#getOnStation').val().trim().split('/')[0]

    const t = $('#toStation').val().trim().split('/')[0]

    const d = $('#date').val().trim()

    const passengers = $('.passengers-check:checked').map((i, item)=>item.value).toArray()

    const seats = $('.seat-checkbox:checked').map((index, item)=>$(item).val())

    if(passengers.length === 0 || seats.length === 0 || no === '') {
        alert('选中乘车人、车次和座位。')
        return
    }

    config = {
        seats: seats,   // O, 3, 4
        data: d,
        trainNo: no,  // k92, g2794,
        from: f,
        to: t,
        fromCode: stationObj.getStationCode(f),
        toCode: stationObj.getStationCode(t),
        selectPassengers: passengers,
    }
    const displayValue = $("#ticketLogContent").css("display");
    if (displayValue === "none") {
        $("#ticketLogContent").toggle("show");
    }

    const loginName = $('#loginName').val().trim()
    const lastCode = $('#lastCode').val().trim()

    if(loginName !== '' && lastCode !== '') {
        globalConfig.messageConfig.username = loginName
        globalConfig.messageConfig.castNum = lastCode
        chrome.storage.local.set({ 'loginName': loginName }, ()=>{})
        chrome.storage.local.set({ 'lastCode': lastCode }, ()=>{})
    }


    utils.outToPlain('开始抢票......')

    s = ''
    for (i =0; i<seats.length;i++)
        s += seatsKey[seats[i]] + ', '

    p = ""
    for (i = 0; i < passengers.length; i++)
        p += globalConfig.passengers[passengers[i]].passenger_name + ', '

    utils.outToPlain(`
    设定目标：
        日期：${d}, 车次：${no}， 
        上车点：${f}， 下车点：${t}, 
        座位：${s}
        乘车人: ${p}
        请等待。。。
    `)
    utils.startTask(config)
    $('#tab1 #startTask').prop('disabled', true)
})

$('#stopTask').click(async ()=>{
    utils.log('stopTask => 停止抢票')
    utils.stopTask()
    utils.outToPlain('停止抢票......')
})

// $("#login-frame").dialog({
//     autoOpen: false,    // 关闭时自动打开
//     modal: true,        // 模态对话框
//     buttons: {
//         "Close": function() {
//             $(this).dialog("close");
//         }
//     },
//     close: function(event, ui) {
//         console.log('Dialog has been closed');
//         // 在这里可以执行对话框关闭时需要的操作
//     }
// });

function storeSearchHistory(key, value) {

    configStore.get(['searchHistory'], function (result) {
        const history = result.searchHistory ? JSON.parse(result.searchHistory) : {}
        delete history[key]
        history[key] = value
        searchHistory = history
        // configStore.set('searchHistory', JSON.stringify(searchHistory))
        chrome.storage.local.set({ 'searchHistory': JSON.stringify(searchHistory) }, ()=>{})
        showHistory()
    })

}

function deleteSearchKey(k) {
    delete searchHistory[k]
    chrome.storage.local.set({ 'searchHistory': JSON.stringify(searchHistory) }, ()=>{})
    showHistory()
}

function showHistory() {
    $('#searchHistoryList').empty()
    for(const k of Object.keys(searchHistory).reverse()) {
        const [on, to] = searchHistory[k].split(',')
        const html = `
                    <a class="history-item link-secondary" href="#">${on} --> ${to}
                    <i class="bi bi-trash3" style="color: red"></i>
                    </a>
                    `
        const a = $(html).click(function () {
            console.log(on, to)
            $('#getOnStation').val(on)
            $('#toStation').val(to)
        })
        $(a).find('i').click(function (){
            console.log('delete :', k)
            deleteSearchKey(k)
        })
        $('#searchHistoryList').append(a)
    }
}

// 查询票数
$('#search').click(async ()=>{

    const f = $('#getOnStation').val().trim()
    const t = $('#toStation').val().trim()
    const d = $('#date').val().trim()

    storeSearchHistory(f + '/' + t, f + ',' + t)

    if(f === '' || t === '' || d === '') {
        utils.log('search => ', f, t, d)
        return
    }

    chrome.storage.local.set({ 'from': f }, ()=>{
        $('#getOnStationAll').val(f)
    })
    chrome.storage.local.set({ 'to': t }, ()=>{
        $('#toStationAll').val(t)
    })
    chrome.storage.local.set({ 'date': d }, ()=>{})

    const tableBody = $('#ticketList tbody');
    tableBody.empty()

    ticketApi.queryTickets(stationObj.getStationCode(f.split('/')[0]), stationObj.getStationCode(t.split('/')[0]), d)
        .then(async data=> {
        searchParams.ticketsData = data
        $.each(data.result, function (index, item) {
            const row = $('<tr>');
            const a = $(`<td><a href="#" data-bs-toggle="modal" data-bs-target="#trainStationModal"
                        value="${item.trainNo}">${item.trainNo}</a></td>`).click(event=>{
                searchTrainStation(this.trainNo, this.trainNumber, this.getOnstation, this.passingBy, utils.getDate(this.date))
            })

            const allDate = $(`
                        <a href="#" data-bs-toggle="modal" data-bs-target="#queryAllByDate" value="${item.trainNo}">所有日期 | </a>
                        `).click(event=>{
                searchAllByDate(this.trainNo, this.getOnstation, this.passingBy)
            })
            const price = $(`
                        <a href="#" data-bs-toggle="modal" data-bs-target="#queryAllByPrice" value="${item.trainNo}">比价</a>
                        `).click(event=>{
                queryAllPrice(this.trainNumber, d, f.split('/')[0], t.split('/')[0], this.trainNo)
            })

            row.append($(`<td>`).text(++index))
            row.append(a)
            row.append($('<td>').text(stationObj.getStationName(item.getOnstation)))
            row.append($('<td>').text(stationObj.getStationName(item.passingBy)))
            row.append($('<td>').text(item.startTime))
            row.append($('<td>').text(item.endTime))
            row.append($('<td>').text(item.time))
            row.append($(`<td style="${ticketCss(item.secondClass)}">${item.secondClass} ${utils.price(item.priceText)['O'] || ''}</td>`))
            row.append($(`<td style="${ticketCss(item.hardSleeper)}">${item.hardSleeper} ${utils.price(item.priceText)['3'] || ''}</td>`))
            row.append($(`<td style="${ticketCss(item.softSleeper)}">${item.softSleeper} ${utils.price(item.priceText)['4'] || ''}</td>`))
            row.append($(`<td style="${ticketCss(item.hardClass)}">${item.hardClass} ${utils.price(item.priceText)['1'] || ''}</td>`))
            row.append($(`<td style="${ticketCss(item.noneClass)}">${item.noneClass} ${utils.price(item.priceText)['W'] || ''}</td>`))
            row.append($(`<td style="${ticketCss(item.firstClass)}">${item.firstClass} ${utils.price(item.priceText)['M'] || ''}</td>`))
            row.append($('<td>').text(item.sellTime))

            const lastRow = $('<td>')
            row.append(lastRow)
            lastRow.append(allDate)
            lastRow.append(price)

            tableBody.append(row);
        });

        const trainNoSelect = $('#trainNoSelect')
        const first = trainNoSelect.children()[0]
        trainNoSelect.empty()
        trainNoSelect.append($(first))
        $.each(data.result, (index, item)=>{
            trainNoSelect.append($(`<option value="${item.trainNo}" startTime="${item.startTime}">${item.trainNo}</option>`))
        })

        const timeInterval = $('#timeInterval')
        const fti = timeInterval.children()[0]
        timeInterval.empty()
        timeInterval.append($(fti))
        searchParams.clear()
        $.each([...new Set(data.result.map(e=>e.startTime.split(':')[0]))], (index, item)=>{
            timeInterval.append($(`<option value="${item}">${item} ~  ${('0' + (parseInt(item) + 1)).slice(-2)}</option>`))
        })

        const trainCheckContainer = $("#trainCheckContainer")
        trainCheckContainer.empty()
        trainMap = data['map']
        getOnstation = [...new Set(data.result.map(e=>e.getOnstation))].map(e=>{return {type: '0', name: e}})
        passingBy = [...new Set(data.result.map(e=>e.passingBy))].map(e=>{return {type: '1', name: e}})
        $.each(getOnstation.concat(passingBy), (index, item)=>{
            const trainCheck = $('<div>')
            trainCheck.attr('class', 'form-check ml-2')
            trainCheck.append(`<input class="form-check-input train-checkbox" type="checkbox" value="${item.type}:${trainMap[item.name]}" id="trainCheckbox${index}"  style="margin-left: 10px">
                            <label class="form-check-label" for="trainCheckbox${index}">
                                ${trainMap[item.name]}
                            </label>`)
            trainCheckContainer.append(trainCheck)
            trainCheck.change(function() {
                // 获取所有选中的复选框的值
                searchParams.stations = $('.train-checkbox:checked').map(function() {
                    return $(this).val();
                }).get();
            });
        })
    })

})

$('#searchSwap').click(function () {
    const f = $('#getOnStation').val().trim()
    const t = $('#toStation').val().trim()

    $('#getOnStation').val(t)
    $('#toStation').val(f)
    console.log('searchSwap')
})


function searchTrainStation(trainNo, no, f, t, d) {

    const td = function (item) {
        // console.log(item)
        // const c = {
        //     'font-weight': 'normal', // bold
        // }
        let color = '#b2afaf'
        let fontWeight = 'normal'
        if(item.isEnabled) {
            color = 'black'
            // fontWeight = 'bold'
        }
        // return Object.keys(c).map(e=>e + ':' + c[e]).join(';')
        return $(`<td style="color: ${color}; font-weight: ${fontWeight}">`)
    }

    $('#trainStationModal .trainTitle').text(trainNo + ' ')

    const tableBody = $('#trainStationModal #trainStationTable tbody')
    tableBody.empty()

    ticketApi.queryByTrainNo(d, no, f, t).then(trainData=>{

        $.each(trainData, function (index, item) {
            const row = $(`<tr>`);
            row.append(td(item).text(++index))
            row.append(td(item).text(item.station_name))
            row.append(td(item).text(item.start_time))
            row.append(td(item).text(item.stopover_time))
            tableBody.append(row);
        });
        utils.log(trainData)
    })
}

$('#timeInterval').change((event)=>{
    searchParams.timeInterval = event.target.value
})

$('#searchAll').click(async ()=>{
    const no = $('#trainNoAll').val().trim()
    const f = $('#getOnStationAll').val().trim()
    const t = $('#toStationAll').val().trim()
    let d = addDaysByYear(new Date(), 0)

    if(f === '' || t === '' || d === '' || no === '') {
        return
    }

    chrome.storage.local.set({ 'trainNo': no }, ()=>{})

    const tableBody = $('#ticketListAllTable tbody')
    tableBody.empty()

    for (i = 0; i < 15; i++) {
        const data = await ticketApi.leftTicketQuery(stationObj.getStationCode(f.split('/')[0]),
            stationObj.getStationCode(t.split('/')[0]), d)
        const item = data.filter(e=>e.trainNo === no.toUpperCase())[0] || {}

        a = $(`<td><a href="#" data-bs-toggle="modal" data-bs-target="#trainStationModal" href="#"  
                        value="${item.trainNo}">${item.trainNo||'-'}</a></td>`).click(event=>{
                            console.log(item)
            searchTrainStation(item.trainNo, item.trainNumber, item.getOnstation, item.passingBy, utils.getDate(item.date))
        })
        const row = $('<tr>');
        row.append($(`<td>${d}</td>`))
        row.append(a)
        // row.append($(`<td><a href="#" value="${item.trainNo}">${item.trainNo || '-'}</a></td>`))
        row.append($('<td>').text(stationObj.getStationName(item.getOnstation)))
        row.append($('<td>').text(stationObj.getStationName(item.passingBy)))
        row.append($('<td>').text(item.startTime))
        row.append($('<td>').text(item.endTime))
        row.append($('<td>').text(item.time))
        row.append($(`<td style="${ticketCss(item.secondClass)}">${item.secondClass || '-'}</td>`))
        row.append($(`<td style="${ticketCss(item.hardSleeper)}">${item.hardSleeper || '-'}</td>`))
        row.append($(`<td style="${ticketCss(item.softSleeper)}">${item.softSleeper || '-'}</td>`))
        row.append($(`<td style="${ticketCss(item.hardClass)}">${item.hardClass || '-'}</td>`))
        row.append($(`<td style="${ticketCss(item.noneClass)}">${item.noneClass || '-'}</td>`))
        row.append($(`<td style="${ticketCss(item.firstClass)}">${item.firstClass || '-'}</td>`))
        row.append($('<td>').text(item.sellTime))
        tableBody.append(row);
        d = addDaysByYear(new Date(), i + 1)
    }

})


async function searchAllByDate(trainNo, from, to) {

    let d = addDaysByYear(new Date(), 0)
    const f = $('#getOnStationAll').val().trim()
    const t = $('#toStationAll').val().trim()

    const tableBody = $('#queryAllByDate table tbody')
    tableBody.empty()

    for (i = 0; i < 15; i++) {
        const data = await ticketApi.leftTicketQuery(from, to, d)
        const item = data.filter(e=>e.trainNo === trainNo.toUpperCase())[0] || undefined
        if(item) {
            a = $(`<td><a href="#" data-bs-toggle="modal" data-bs-target="#trainStationModal" href="#"  
                            value="${item.trainNo}">${item.trainNo||'-'}</a></td>`).click(event=>{
                console.log(item)
                searchTrainStation(item.trainNo, item.trainNumber, item.getOnstation, item.passingBy, utils.getDate(item.date))
            })
            const row = $('<tr>');
            row.append($(`<td>${d}</td>`))
            row.append(a)
            // row.append($(`<td><a href="#" value="${item.trainNo}">${item.trainNo || '-'}</a></td>`))
            row.append($('<td>').text(stationObj.getStationName(item.getOnstation)))
            row.append($('<td>').text(stationObj.getStationName(item.passingBy)))
            row.append($('<td>').text(item.startTime))
            row.append($('<td>').text(item.endTime))
            row.append($('<td>').text(item.time))
            row.append($(`<td style="${ticketCss(item.secondClass)}">${item.secondClass || '-'}</td>`))
            row.append($(`<td style="${ticketCss(item.hardSleeper)}">${item.hardSleeper || '-'}</td>`))
            row.append($(`<td style="${ticketCss(item.softSleeper)}">${item.softSleeper || '-'}</td>`))
            row.append($(`<td style="${ticketCss(item.hardClass)}">${item.hardClass || '-'}</td>`))
            row.append($(`<td style="${ticketCss(item.noneClass)}">${item.noneClass || '-'}</td>`))
            row.append($(`<td style="${ticketCss(item.firstClass)}">${item.firstClass || '-'}</td>`))
            row.append($('<td>').text(item.sellTime))
            tableBody.append(row);
        }
        d = addDaysByYear(new Date(), i + 1)
    }
}

async function queryAllPrice(trainNumber, date, form, to, trainOn) {

    console.log(trainNumber, date, form, to)

    const tbody = $('#queryAllByPrice table tbody')
    tbody.empty()

    const title = $('#queryAllByPrice .trainTitle')
    title.text(trainOn)

    ticketApi.queryByTrainNo(date, trainNumber, stationObj.getStationCode(form), stationObj.getStationCode(to)).then(async data=>{
        const startTrainInfo = data[0]

        const trainStationList = $('#queryAllByPrice .trainStation .list-group')
        trainStationList.empty()
        $.each(data, function (index, item) {
            // const row = $(`<div>`);
            trainStationList.append($(`<li class="list-group-item">
                <input class="form-check-input me-1" type="checkbox" value="${item.station_name}" id="firstCheckbox${index}">
                <label class="form-check-label" for="firstCheckbox${index}">${item.station_name}</label>
                </li>
            `))
        });

        prices = []
        for(let i = 1; i < data.length; i++) {
            const t = stationObj.getStationCode(data[i].station_name)
            const tickets = await ticketApi.leftTicketQuery(stationObj.getStationCode(startTrainInfo.station_name), t, date)
            const ticket = tickets.filter(f=>f.trainNumber === trainNumber)
            if(ticket.length > 0) {
                ticket[0].prices = utils.price(ticket[0].priceText)
                prices.push(ticket[0])
                const row = $('<tr>');
                tbody.append(row)
                row.append($('<td>').text(startTrainInfo.station_name))
                row.append($('<td>').text(data[i].station_name))
                row.append($('<td>').html(ticket[0].prices['O']))
                row.append($('<td>').html(ticket[0].prices['3']))
                row.append($('<td>').html(ticket[0].prices['4']))
                row.append($('<td>').html(ticket[0].prices['1']))
                row.append($('<td>').html(ticket[0].prices['W']))
                row.append($('<td>').html(ticket[0].prices['M']))
            }
            // break
            await utils.sleep(0.2)
        }


    })
}

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        if(details.url.startsWith('chrome-extension://')) {
            // return {cancel: true};
        }
        if(details.url.indexOf('img.bosszhipin.com') !== -1) {
            // return {cancel: true}; 
        }
        if(details.url.indexOf('.png') !== -1 || details.url.indexOf('.jpeg') !== -1 || details.url.indexOf('.jpg') !== -1) {
            // return {cancel: true}; 
        }
        if(details.url.indexOf('www.youtube.com/youtubei/v1/browse') !== -1) {
            console.log('before-request', details.url)
            // alert(JSON.stringify(details.requestBody))
            console.log(details, details.requestBody.raw[0])
            const textDecoder = new TextDecoder('utf-8');
            const resultString = textDecoder.decode(new Uint8Array(details.requestBody.raw[0]));

            console.log(resultString); // 输出: "Hello"
        }
        if(details.url.indexOf('12306.cn/') !== -1 ) {
            if(
                details.url.indexOf('/otn/confirmPassenger/confirmSingleForQueue') > -1 
            ) {
                data = {
                    url: details.url,
                    params: details.requestBody,
                    headers: details.extraHeaders
                }
                console.log(data)
                // return {cancel: true};
            }
            // console.log(details, details.requestBody.raw[0])
            // const textDecoder = new TextDecoder('utf-8');
            // const resultString = textDecoder.decode(new Uint8Array(details.requestBody.raw[0]));

            // console.log(resultString); // 输出: "Hello"
            
        }

      // 在此处可以拦截请求或修改请求

    },
    // { urls: ['<all_urls>'] },
    { urls: ['*://*.12306.cn/*'] },
    ["blocking", "requestBody", 'extraHeaders'],
  );
  
chrome.webRequest.onCompleted.addListener((details)=>{
       console.log('onCompleted', details, details.requestHeaders)
    },
    { urls: ['*://*.12306.com/*'] },
    ['extraHeaders', 'responseHeaders']
)
    
chrome.webRequest.onBeforeSendHeaders.addListener((details)=>{
    generateRandomIp = function () {
        // 生成四个随机数作为IP地址的四个部分
        const part1 = Math.floor(Math.random() * 256);
        const part2 = Math.floor(Math.random() * 256);
        const part3 = Math.floor(Math.random() * 256);
        const part4 = Math.floor(Math.random() * 256);

        // 构建IP地址字符串
        const ipAddress = part1 + '.' + part2 + '.' + part3 + '.' + part4;

        return ipAddress;
    }

    function generateRandomIPv6() {
        let ipv6Address = "";

        for (let i = 0; i < 8; i++) {
          // 生成4个随机的十六进制数字
          const randomSegment = Math.floor(Math.random() * 65536).toString(16);
          ipv6Address += randomSegment;

          // 在每组的末尾添加冒号，除了最后一组
          if (i < 7) {
            ipv6Address += ":";
          }
        }

        return ipv6Address;
    }

    function generateRandomHex(length) {
        const characters = '0123456789ABCDEF';
        let result = '';

        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            result += characters.charAt(randomIndex);
        }

        return result;
    }

    const randomHex = generateRandomHex(32);

        if(details.url.indexOf('kyfw.12306.cn') !== -1) {
            const data = {
                url: details.url,
                headers: details.requestHeaders
            }
            if(
                details.url.indexOf('/otn/leftTicket/query') !== -1 ||
                details.url.indexOf('/otn/czxx/queryByTrainNo') !== -1
                ) {
                    details.requestHeaders.push({ name: "Referer", value: 'https://www.12306.cn' })
                    details.requestHeaders.push({ name: "Origin", value: 'https://www.12306.cn' })
                    details.requestHeaders.push({ name: "X-Requested-With", value: 'XMLHttpRequest' })
                    details.requestHeaders.push({ name: "Cookie", value: `JSESSIONID=; BIGipServerotn=; route=` })
            } else if (
                    details.url.indexOf('/otn/confirmPassenger/getPassengerDTOs') !== -1 ||
                    details.url.indexOf('/otn/confirmPassenger/checkOrderInfo') !== -1 ||
                    details.url.indexOf('/otn/confirmPassenger/getQueueCount') !== -1 ||
                    details.url.indexOf('/otn/confirmPassenger/resultOrderForDcQueue') !== -1 ||
                    details.url.indexOf('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') !== -1
                ) {
                details.requestHeaders.push({ name: "Referer", value: 'https://kyfw.12306.cn/otn/confirmPassenger/initDc' })
                details.requestHeaders.push({ name: "Origin", value: 'https://kyfw.12306.cn' })
                details.requestHeaders.push({ name: "X-Requested-With", value: 'XMLHttpRequest' })
                console.log(data)
            } else if(
                details.url.indexOf('/otn/login/conf') > -1 ||
                details.url.indexOf('/otn/login/checkUser') > -1
                ) {
                details.requestHeaders.push({ name: "Referer", value: 'https://www.12306.cn' })
                details.requestHeaders.push({ name: "Origin", value: 'https://www.12306.cn' })
            } else if(
                details.url.indexOf('/otn/leftTicket/submitOrderRequest') !== -1
                ) {
                    details.requestHeaders.push({ name: "Referer", value: 'https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc' })
                    details.requestHeaders.push({ name: "Origin", value: 'https://kyfw.12306.cn' })
                    details.requestHeaders.push({ name: "X-Requested-With", value: 'XMLHttpRequest' })
            } else if(details.url.indexOf('/otn/index/initMy12306Api') > -1) {
                details.requestHeaders.push({ name: "Referer", value: 'https://kyfw.12306.cn/otn/view/index.html' })
                details.requestHeaders.push({ name: "Origin", value: 'https://kyfw.12306.cn' })
            } else if( details.url.indexOf('/otn/passengers/query') > -1) {
                details.requestHeaders.push({ name: "Referer", value: 'https://kyfw.12306.cn/otn/view/passengers.html' })
                details.requestHeaders.push({ name: "Origin", value: 'https://kyfw.12306.cn' })
            }
            details.requestHeaders.push({ name: "X-Forwarded-For", value: generateRandomIp() })
        }

        // https://kyfw.12306.cn/otn/payOrder/init?random=1704702606538

        return {requestHeaders: details.requestHeaders};
    },
    {urls: ["*://*.12306.cn/*",]},
    ["blocking", 'extraHeaders', 'requestHeaders']
);

// chrome.webRequest.onResponseStarted.addListener(
//     function(details) {
//         console.log('onResponseStarted', details, details.responseHeaders)
//     },
//     {urls: ["https://kyfw.12306.com/*"]},
//     ['extraHeaders',"responseHeaders"]
// );

chrome.webRequest.onResponseStarted.addListener(
    function(details) {
        // details 包含有关请求的信息
        // console.log("Response started:", details);

        // 你可以访问响应头信息
        // console.log("Status code:", details.statusCode);
        // console.log("Response headers:", details.responseHeaders);
    },
    { urls: ["<all_urls>"] }, // 拦截所有 URL 的请求
    ["responseHeaders"] // 允许获取响应头
);

chrome.webRequest.onBeforeRedirect.addListener(
    function(details) {
        if(details.url.includes('/otn/leftTicket/query')) {

            console.log('Redirect detected');
            console.log('From URL:', details.url);
            console.log('To URL:', details.redirectUrl);

            TICKET_URL = details.redirectUrl.split('?')[0]
        }
    },
    { urls: ["<all_urls>"] } // 监听所有 URL 的请求
);


var configStore = {
    set: function (k, value) {
        // 存储数据
        chrome.storage.local.set({ k: value }, function() {
            console.log('Data is stored.')
        })
    },

    get: async function (keys, call) {
        // 检索数据
       chrome.storage.local.get([...keys], (data)=>{
           call(data)
       })
    }


}

function myMenuItemClickHandler(info, tab) {
    // 处理点击事件，根据 info 和 tab 参数执行相应操作
    console.log("右键菜单被点击了！", info, tab);
}

/*
NOTE:



*/